const koa = require('koa');
const bodyParser = require('koa-bodyparser');
const router = require('koa-router')();
const query  = require('./db');
const app = new koa();
let PORT = 3000;

router.get('/getUser', async (ctx, next) => {
    const res = await query('select * from user');
    ctx.body = res;
});
router.post('/addUser', async (ctx, next) => {
    const { name, pwd } = ctx.request.body;
    const res = await query(`insert into user (name, pwd) values ('${name}', '${pwd}')`);
    if(res.affectedRows){
        ctx.body = {code: 0, msg: '成功'};
    } else {
        ctx.body = {code: 1, msg: '失败'};
    }
});
router.post('/delUserById', async (ctx, next) => {
    const { id } = ctx.request.body;
    const res = await query(`delete from user where id = ${id}`);
    if(res.affectedRows){
        ctx.body = {code: 0, msg: '成功'};
    } else {
        ctx.body = {code: 1, msg: '失败'};
    }
});
router.post('/getDataById', async (ctx, next) => {
    const { id } = ctx.request.body;
    const res = await query(`select * from user where id = ${id}`);
    ctx.body = res[0];
});
router.post('/edit', async (ctx, next) => {
    const { id, name, pwd } = ctx.request.body;
    const res = await query(`update user set name='${name}',pwd='${pwd}' where id=${id}`);
    if(res.affectedRows){
        ctx.body = {code: 0, msg: '成功'};
    } else {
        ctx.body = {code: 1, msg: '失败'};
    }
});

app.use(bodyParser());
app.use(router.routes(), router.allowedMethods());
app.listen(PORT, ()=>{ console.log('启动成功，端口：'+PORT); });